<?php
//
// +------------------------------------------------------------------------+
// | PHP Version 5.4                                                        |
// +------------------------------------------------------------------------+
// | Copyright (c) All rights reserved.                                     |
// +------------------------------------------------------------------------+
// | 世纪车来车往(北京）网络科技有限公司 版权所有！                                  |
// | TEL:010-63732365  HOTLINE:400-6688-365  EMAIL:clcw@clcw.com.cn         |
// | $Revision: 1.0 $                                                     |
// +------------------------------------------------------------------------+
// | Author: shaoshuai@clcw.com.cn                                           |
// +------------------------------------------------------------------------+
//
namespace AuctionBack\Controller;

use AuctionCore\Common\AjaxPage;
use AuctionCore\Common\Image;
use AuctionCore\Common\Util;
use AuctionCore\Common\PhpRedis;
use AuctionCore\System\SystemLog;

class ArticleController extends BaseController
{

    protected $articleLogic;

    protected $articleExpertLogic;

    protected $articleCategoryLogic;

    private $empId;

    public function __construct()
    {
        parent::__construct();

        $this->articleLogic = D('Article', 'Logic');

        $this->articleExpertLogic = D('ArticleExpert', 'Logic');

        $this->articleCategoryLogic = D('ArticleCategory', 'Logic');

        $this->empId = $this->user_info['emp_id'];
    }

    /**
     * 资讯管理
     */
    public function index()
    {

        $category = $this->articleCategoryLogic->getParentArticleCategory();
        $this->assign('cate', $category);
        $this->display();

    }

    public function getChildCategory()
    {
        $parentId = I('get.category_id/d', 0);
        $category = $this->articleCategoryLogic->getArticleCategoryByPid($parentId);
        echo json_encode($category);
    }


    /**
     * 资讯列表
     */
    public function articleList()
    {
        $params = [];

        $page = I('get.p', 1);
        $pageSize = 10;
        $params['category_id'] = I('get.category_id');
        $params['child_id'] = I('get.child_id');
        $params['article_title'] = trim(I('get.article_title'));
        $params['type'] = I('get.type');
        $params['attribute'] = I('get.attribute');
        $params['from_name'] = I('get.from_name');
        $params['sort'] = I('request.sort');
        $params['start_time'] = I('request.start_time');
        $params['end_time'] = I('request.end_time');

        if (isset($_GET['status'])) {
            $params['status'] = I('get.status');
        }

        if (isset($_GET['is_top'])) {
            $params['is_top'] = I('get.is_top');
        }

        $data = $this->articleLogic->getArticleList($page, $pageSize, $params);

        $category = $this->articleCategoryLogic->getArticleCategory();

        $cate = [];
        foreach ($category as $v) {
            $cate[$v['category_id']] = $v;
        }

        $Page = new AjaxPage($data['total'], $pageSize, "get_page");
        $Page->setConfig('theme', " %totalRow% %header% %nowPage%/%totalPage% 页 %first% %upPage% %prePage% %linkPage% %nextPage% %downPage%  %end% %jumpform%");
        $show = $Page->show();// 分页显示输出

        $this->assign('date', date('Y-m-d'));
        $this->assign('page', $show);
        $this->assign('article', $data['list']);
        $this->assign('cate', $cate);

        $this->display();

    }

    /**
     * 添加文章
     */
    public function add()
    {
        $id = I('get.id');

        if ($id) {
            $article = $this->articleLogic->getArticleById($id);
            $child = $this->articleCategoryLogic->getArticleCategoryByPid($article['category_id']);
        } else {
            $article = [];
            $child = [];
        }

        $category = $this->articleCategoryLogic->getArticleCategoryByPid(0);

        $this->assign('child', $child);
        $this->assign('article', $article);
        $this->assign('categoty', $category);

        $this->display();
    }

    /**
     * 保存文章
     */
    public function save()
    {
        $data = [
            'id'                => I('post.id'),
            'article_title'     => I('post.title'),
            'author'            => I('post.author'),
            'category_id'       => I('post.category', 0),
            'article_attribute' => I('post.attribute', 1),
            'child_id'          => I('post.child', 0),
            'is_top'            => I('post.top', 0),
            'article_focus'     => I('post.focus'),
            'article_thumb'     => I('post.thumb'),
            'article_desc'      => I('post.desc'),
            'article_content'   => $_POST['content'],
            'cron_time'         => I('post.publish_time')
        ];

        if (!empty($data['cron_time'])) {
            $data['cron_time'] = strtotime($data['cron_time']);
            $data['status'] = 3;
            if ($this->articleLogic->isLockCronPublish()){
                echo Util::auto_jsonp_or_json($_REQUEST, ['code' => '300', 'msg' => '定时发布锁定中,请重试']);
                return;
            }

            $this->articleLogic->LockCronPublish();
        }

        $res = $this->articleLogic->saveArticle($data);

        if ($res) {

            if (!empty($data['id'])) {
                $id = $data['id'];
            } else {
                $id = $res;
            }
            if ($data['status'] == 3) {
                D('Article', 'Logic')->cronPublish($id, $data['cron_time'], '200001');
                $this->articleLogic->unLockCronPublish();
            }
            SystemLog::add(
                [
                    'emp_id' => $this->empId,
                    'action' => '保存资讯'
                ]
            );

            echo Util::auto_jsonp_or_json($_REQUEST, [
                    'code' => '200',
                    'msg'  => '资讯保存成功',
                    'data' => $res
                ]
            );
            die;
        } else {
            echo Util::auto_jsonp_or_json($_REQUEST, [
                    'code' => '5',
                    'msg'  => '资讯保存失败,请重试!',
                    'data' => $res
                ]
            );
            die;
        }
    }

    /**
     * 文章预览
     */
    public function show()
    {
        $articleId = I('get.id');

        $article = $this->articleLogic->getArticleById($articleId);
        $article['create_time'] = date('Y-m-d H:i:s', $article['create_time']);
        if ($article['type'] == 1) {

            $category = D('ArticleCategory', 'Logic')->getArticleCategoryById($article['category_id']);
            $childCategory = D('ArticleCategory', 'Logic')->getArticleCategoryById($article['child_id']);

            $categoryName = $category['category_title'] . '-' . $childCategory['category_title'];

        } else {
            $categoryName = $article['from_name'];
        }
        $this->assign('categoryName', $categoryName);
        $this->assign('article', $article);
        $this->display();
    }

    /**
     * 牛人日报预览
     */
    public function showExpert()
    {
        $articleId = I('get.id');
        $article = $this->articleExpertLogic->getExpertArticleById($articleId);
        $article['create_time'] = date('Y-m-d H:i:s', $article['create_time']);
        $author = $this->articleExpertLogic->getExpertAuthorById($article['user_id']);

        $this->assign('author', $author);
        $this->assign('article', $article);
        $this->display();
    }

    /**
     * 修改文章状态
     */
    public function changeStatus()
    {
        $id = I('post.id');
        $status = I('post.status');
        if ($id && isset($_REQUEST['status'])) {
            $time = time();
            $data = [
                'id'           => $id,
                'status'       => $status,
                'update_time'  => $time,
            ];
            if ($status != 0) {
                $data['publish_time'] = $time;
            }
            $res = $this->articleLogic->saveArticle($data);

            if ($res) {
                SystemLog::add(['emp_id' => $this->empId, 'action' => '修改资讯状态']);
                echo Util::auto_jsonp_or_json($_REQUEST, ['code' => '200', 'msg' => '']);
                die;
            }
        }
        echo Util::auto_jsonp_or_json($_REQUEST, ['code' => '5', 'msg' => '']);
        die;
    }

    /**
     * 牛人日报管理
     */
    public function expert()
    {
        $this->display();
    }

    /**
     * 牛人日报列表
     */
    public function expertArticleList()
    {
        $page = I('get.p', 1);
        $sort = I('request.sort');
        $pageSize = 10;

        $params = [];
        if (isset($_GET['status'])) {
            $params['status'] = I('get.status');
        }
        if (isset($_GET['is_top'])) {
            $params['is_top'] = I('get.is_top');
        }
        if ($sort) {
            $params['sort'] = $sort;
        }

        $params['article_title'] = trim(I('get.article_title'));
        $params['nick_name'] = trim(I('get.nick_name'));
        $params['attribute'] = trim(I('get.attribute'));
        $params['start_time'] = I('request.start_time');
        $params['end_time'] = I('request.end_time');
        $data = $this->articleExpertLogic->getExpertArticleList($params, $page, $pageSize);
        $Page = new AjaxPage($data['total'], $pageSize, "get_page");
        $Page->setConfig('theme', " %totalRow% %header% %nowPage%/%totalPage% 页 %first% %upPage% %prePage% %linkPage% %nextPage% %downPage%  %end% %jumpform%");
        $show = $Page->show();// 分页显示输出

        $this->assign('page', $show);
        $this->assign('article', $data['list']);

        $this->display();

    }

    /**
     * 新增日报
     */
    public function expertAdd()
    {
        $id = I('get.id');

        if ($id) {
            $article = $this->articleExpertLogic->getExpertArticleByID($id);
        } else {
            $article = [];
        }

        $author = $this->articleExpertLogic->getExpertUserList();

        $this->assign('author', $author);
        $this->assign('article', $article);

        $this->display();
    }

    /**
     * 保存牛人日报
     */
    public function saveExpert()
    {

        $data = [
            'id'              => I('post.id'),
            'article_title'   => I('post.title'),
            'article_attribute' => I('post.attribute', 1),
            'is_top'          => I('post.top'),
            'user_id'         => I('post.author'),
            'article_focus'   => I('post.focus'),
            'article_thumb'   => I('post.thumb'),
            'article_desc'    => I('post.desc'),
            'article_content' => $_POST['content'],
            'cron_time'       => I('post.publish_time')
        ];

        if (!empty($data['cron_time'])) {
            $data['cron_time'] = strtotime($data['cron_time']);
            $data['status'] = 3;
            if ($this->articleLogic->isLockCronPublish()){
                echo Util::auto_jsonp_or_json($_REQUEST, ['code' => '300', 'msg' => '定时发布锁定中,请重试']);
                return;
            }

            $this->articleLogic->LockCronPublish();
        }
        $res = $this->articleExpertLogic->saveExpertArticle($data);

        if ($res) {

            if (!empty($data['id'])) {
                $id = $data['id'];
            } else {
                $id = $res;
            }
            if ($data['status'] == 3) {
                D('Article', 'Logic')->cronPublish($id, $data['cron_time'], '200002');
                $this->articleLogic->unlockCronPublish();
            }
            SystemLog::add(
                [
                    'emp_id' => $this->empId,
                    'action' => '保存资讯'
                ]
            );

            SystemLog::add(['emp_id' => $this->empId, 'action' => '保存牛人日报']);
            echo Util::auto_jsonp_or_json($_REQUEST, ['code' => '200', 'msg' => '日报保存成功']);
            die;
        } else {
            echo Util::auto_jsonp_or_json($_REQUEST, ['code' => '5', 'msg' => '日报保存失败,请重试!']);
            die;
        }
    }

    /**
     * 修改文章状态
     */
    public function changeExpertStatus()
    {
        $id = I('post.id');
        $status = I('post.status');
        if (!isset($_POST['status'])) {
            echo Util::auto_jsonp_or_json($_REQUEST, ['code' => '200', 'msg' => '']);
            die;
        }

        if ($id) {
            $time = time();
            $data = [
                'id'           => $id,
                'status'       => $status,
                'update_time'  => $time,
                'publish_time' => $time
            ];
            $res = $this->articleExpertLogic->saveExpertArticle($data);

            if ($res) {
                SystemLog::add(['emp_id' => $this->empId, 'action' => '修改牛人日报状态']);
                echo Util::auto_jsonp_or_json($_REQUEST, ['code' => '200', 'msg' => '']);
                die;
            }
        }
        echo Util::auto_jsonp_or_json($_REQUEST, ['code' => '5', 'msg' => '']);
        die;
    }

    public function ueditor()
    {
        $ret = [];
        foreach ($_FILES as $key => $file) {
            $tmpFile = $file['tmp_name'];
            $object = $tmpFile . '.' . get_extension($file['name']);
            $ret[] = Image::upload_file_by_file(OSS_BUCKET, $object, $tmpFile, null, '', 'article');
        }

        $data = [
            "error"    => 0,          //上传状态，上传成功时必须返回"SUCCESS"
            "url"      => 'http:' . get_content_cdnurl() . current($ret),            //返回的地址
        ];
        echo json_encode($data);
    }

    public function uploadPic()
    {
        try {
            $ret = [];
            foreach ($_FILES as $key => $file) {
                $tmpFile = $file['tmp_name'];
                $object = $tmpFile . '.' . get_extension($file['name']);
                $ret[] = Image::upload_file_by_file(OSS_BUCKET, $object, $tmpFile, null, '', 'carousel');
            }
            echo Util::auto_jsonp_or_json($_REQUEST, ['code' => '200', 'msg' => '', 'data' => $ret]);
            exit;
        } catch (\Exception $e) {
            echo Util::auto_jsonp_or_json($_REQUEST, ['code' => '5', 'msg' => $e->getMessage()]);
            exit;
        }
    }


    /**
     * 文章分类管理
     */
    public function categoryList()
    {
//        $result = M('article_category', 'clcw_', 'DB_CLCW')->order('parent_id ASC')->select();
        $result = $this->articleCategoryLogic->getArticleCategory();
        $data = [];

        foreach ($result as $v) {
            if ($v['parent_id'] == 0) {
                $data[$v['category_id']] = $v;
            } else {
                $data[$v['parent_id']]['child'][] = $v;
            }
        }
        $this->assign('category', $data);
        $this->display();

    }

    /**
     * 编辑文章分类
     */
    public function editCategory()
    {
        $id = I('get.id');
        $parentId = I('get.parent_id');

//        $parent = M('article_category', 'clcw_', 'DB_CLCW')->where(['parent_id' => 0])->select();
        $parent = $this->articleCategoryLogic->getParentArticleCategory();

        if ($id) {
//            $category = M('article_category', 'clcw_', 'DB_CLCW')->where(['category_id' => $id])->find();
            $category = $this->articleCategoryLogic->getArticleCategoryById($id);
        } else {
            $category = [];
        }

        $this->assign('category', $category);
        $this->assign('parent', $parent);
        $this->display();
    }

    public function saveCategory()
    {
        $id = I('post.category_id');
        $categoryTitle = I('post.category_title');
        $parentId = I('post.parent_id');

        if ($id) {
            /*
            $res = M('article_category', 'clcw_', 'DB_CLCW')->where(['category_id' => $id])->save(
                [
                    'category_title' => $categoryTitle,
                    'parent_id'      => $parentId,
                    'update_time'    => NOW_TIME
                ]
            );
            */
            $data = [
                'category_title' => $categoryTitle,
                'parent_id'      => $parentId,
                'update_time'    => NOW_TIME
            ];
            $res = $this->articleCategoryLogic->saveArticleCategory($id, $data);
        } else {
            /*
            $res = M('article_category', 'clcw_', 'DB_CLCW')->add(
                [
                    'category_title' => $categoryTitle,
                    'parent_id'      => $parentId,
                    'create_time'    => NOW_TIME
                ]
            );
            */
            $data = [
                'category_title' => $categoryTitle,
                'parent_id'      => $parentId,
                'create_time'    => NOW_TIME
            ];
            $res = $this->articleCategoryLogic->addArticleCategory($data);
        }

        if ($res) {
            SystemLog::add(['emp_id' => $this->empId, 'action' => '保存文章分类']);
            $this->helpJsonResult(200, '添加成功');
        } else {
            $this->helpJsonResult(500, '添加失败');
        }
    }

}
